#include "Acceptor.h"
#include "log.h"
#include "InetAddress.h"

#include <sys/types.h>    
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
static int createNonblocking()
{
    int sockfd = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
    if (sockfd < 0)
    {
        LOG_FATAL("%s:%s:%d socket errror %d \n", __FILE__, __FUNCTION__, __LINE__, errno);
    }
    
    return sockfd;
}
Acceptor::Acceptor(EventLoop *loop, const InetAddress &listenAddr, bool reuseport)
    : loop_(loop), acceptSocket_(createNonblocking()), acceptChannel_(loop_, acceptSocket_.fd()), listenning_(false)
{
    acceptSocket_.setReuseAddr(true);
    acceptSocket_.serReusePort(true);
    acceptSocket_.bindAddress(listenAddr);
    //当有新用户的链接需要执行一个回调  
    acceptChannel_.ReadCallBack(std::bind(&Acceptor::headleRead, this));
}
Acceptor::~Acceptor() {
    acceptChannel_.disableAll();
    acceptChannel_.remove();
};

void Acceptor::listen() {
    listenning_=true;
    acceptSocket_.listen();
    acceptChannel_.enableReading();//

};
//listenfd可读，有新用户连接
void Acceptor::headleRead()
{
    InetAddress peerAddr;
    int connfd = acceptSocket_.accept(&peerAddr);
    if (connfd >= 0)
    {
        if (newConnectionCallback_)
        {
            newConnectionCallback_(connfd, peerAddr);//轮询找到subloop唤醒,分发当前新客户端的channel
        }
        else
        {
            ::close(connfd);
        }
    }
    else
    {
        LOG_FATAL("%s:%s:%d accept errror %d \n", __FILE__, __FUNCTION__, __LINE__, errno);
        if (errno == EMFILE)
        {
            LOG_FATAL("%s:%s:%d socket reached limit %d \n", __FILE__, __FUNCTION__, __LINE__, errno);
        }
    }
};
